package com.lxw.myeverything.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
    /**
     * 扫描指定路径下的文件
     *
     * @param file
     * @param files
     */
    public static List<File> getFiles(File file, List<File> files) {
        File[] fs = file.listFiles();
        if (fs != null && fs.length>0) {
            for (File f : fs) {
                if (f.isFile()) {
                    files.add(f);
                } else {
                    getFiles(f, files);
                }
            }
        }
        return files;
    }

    /**
     * 逐行读取
     *
     * @param fin
     * @throws IOException
     */
    public static List<String> readFileByLine(File fin) throws IOException {
        List<String> list = new ArrayList<>();
        BufferedReader br = new BufferedReader(new FileReader(fin));
        String line;
        while ((line = br.readLine()) != null) {
            list.add(line);
        }
        br.close();
        return list;
    }

    public static void write2File(File file, List<String> lines) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        for (String line : lines) {
            bw.write(line+"\n");
        }
        bw.flush();
        bw.close();
    }
    public static void write2File(File file, String line) throws IOException {
        BufferedWriter bw = new BufferedWriter(new FileWriter(file));
        bw.write(line+"\n");
        bw.flush();
        bw.close();
    }

    public static void main(String[] args) {
        List<File> list = new ArrayList<>();
        File file = new File("E:\\idea");
        getFiles(file, list);
        for (File f : list) {
            String name = f.getName();
            if ("vue.js".equals(name)) {
                System.out.println(f.getAbsoluteFile());
            }
        }
    }
}
